package com.jfinal.weixin.demo.web;

import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.JsTicketApi;
import com.jfinal.weixin.sdk.api.SnsAccessToken;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;
import com.jfinal.weixin.sdk.encrypt.AesException;
import com.jfinal.weixin.sdk.encrypt.SHA1;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.UUID;

/**
 * Created by loocao on 15/8/11.
 */
public class TestController extends Controller {

    /**
     * 如果要支持多公众账号，只需要在此返回各个公众号对应的  ApiConfig 对象即可
     * 可以通过在请求 url 中挂参数来动态从数据库中获取 ApiConfig 属性值
     */
    public ApiConfig getApiConfig() {
        ApiConfig ac = new ApiConfig();

        // 配置微信 API 相关常量
        ac.setToken(PropKit.get("token"));
        ac.setAppId(PropKit.get("appId"));
        ac.setAppSecret(PropKit.get("appSecret"));

        /**
         *  是否对消息进行加密，对应于微信平台的消息加解密方式：
         *  1：true进行加密且必须配置 encodingAesKey
         *  2：false采用明文模式，同时也支持混合模式
         */
        ac.setEncryptMessage(PropKit.getBoolean("encryptMessage", false));
        ac.setEncodingAesKey(PropKit.get("encodingAesKey", "setting it in config file"));
        return ac;
    }

    public void index() {
        ApiConfigKit.setThreadLocalApiConfig(getApiConfig());
        String code = getPara("code");
        if (code == null || code.length() == 0) {
            try {
                String encodeUrl = URLEncoder.encode("http://ibuy.kunter.cn/weixin/test", "UTF-8");
                redirect(redirectAuthUrl(encodeUrl));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        } else {
            SnsAccessToken accessToken = SnsAccessTokenApi.getSnsAccessToken(PropKit.get("appId"), PropKit.get("appSecret"),
                    code);
            setAttr("accessToken", accessToken);

            setAttr("appId", PropKit.get("appId"));
            ApiResult apiResult = JsTicketApi.getTicket();
            String nonceStr = "noncestr=" + UUID.randomUUID().toString();
            String jsapi_ticket = "jsapi_ticket=" + apiResult.getStr("token");
            String timestamp = String.valueOf(new Date().getTime());
            String url = "url=http://ibuy.kunter.cn/weixin/test";
            try {
                String signature = SHA1.getSignature(jsapi_ticket, timestamp, nonceStr, url);

                setAttr("signature", signature);
                setAttr("timestamp", timestamp);
                setAttr("nonceStr", nonceStr);

                render("index.html");
            } catch (AesException e) {
                e.printStackTrace();
            }
        }
    }

    private String redirectAuthUrl(String str) {
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s" +
                "&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
        return String.format(url, PropKit.get("appId"), str);
    }

}
